package com.jmlee.controller;

import com.jmlee.bo.WxUserInfoBO;
import com.jmlee.exception.Asserts;
import com.jmlee.pojo.CommonResult;
import com.jmlee.pojo.Users;
import com.jmlee.service.UsersService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;

/**
 * @Description 前台用户授权认证服务接口
 * @Author jmLee
 * @Date 2021/3/5 14:00
 * @Version 1.0
 */
@RestController
public class AuthController {

    // 从微信公众平台上获取
    String appId = "wx1fb582c8b3276783";
    // 在微信公众平台上生成
    String secret = "7fbeea3dac4b7a0084a3f2879009e235";


    @Autowired
    private UsersService usersService;


    @GetMapping("/login")
    public CommonResult login(@RequestParam("code") String code) {

        if (StringUtils.isBlank(code) || StringUtils.isBlank(code)) {
            Asserts.fail("code不能为空");
        }
        // 返回openId和sessionKey
        String res = getOpenIdAndSessionKey(code);

        if (res != null) {
            return CommonResult.success(res, "ok");
        }

        return CommonResult.failed("openId与sessionkey获取失败");
    }


    @PostMapping("/register")
    public CommonResult register(@RequestBody WxUserInfoBO wxUserInfoBO) {

        Users user = new Users();
        user.setHeadImg(wxUserInfoBO.getAvatarUrl());
        user.setUsername(wxUserInfoBO.getNickName());
        user.setOpenid(wxUserInfoBO.getOpenid());
        user.setNickname(wxUserInfoBO.getNickName());
        user.setCreateTime(new Date());

        Long userId = usersService.addUser(user);

        return CommonResult.success(userId, "ok");
    }

    /**
     * 前往微信后台获取openid和session_key
     *
     * @param code
     * @return
     */
    private String getOpenIdAndSessionKey(String code) {


        /**
         * "GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
         */
        String checkUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;

        String result = null;

        try {
            // 创建 Http Get请求
            HttpGet httpGet = new HttpGet(checkUrl);
            // 创建请求对象
            client = HttpClients.createDefault();

            // 执行请求
            response = client.execute(httpGet);

            // 获取返回数据
            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity);


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

}
